import store from '@/store';
import { createRouter, createWebHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import userRoutes from './module/user';
import { Alert } from '../components/message';

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      title: 'eQuantum',
    },
  },
  {
    path: '/learn',
    name: 'learn',
    component: () => import('../views/LearnView.vue'),
    meta: {
      title: 'eQuantum',
    },
  },
  {
    path: '/composer',
    name: 'composer',
    component: () => import('../views/ComposerView.vue'),
    meta: {
      title: 'eQuantum',
      auth: true,
    },
  },
  {
    path: '/download',
    name: 'download',
    component: () => import('../views/DownloadView.vue'),
    meta: {
      title: 'eQuantum',
    },
  },
  ...userRoutes,
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.meta.auth) { // 判断是否需要登录
    // 判断用户是否登录
    if (store.state.userModule.token) {
      // TODO：判断token的有效性
      next();
    } else {
      // 提示用户登录
      Alert('继续使用实验平台，需要您登录');
      // 跳转登录页面
      router.push({ name: 'login' });
    }
  } else next();
});

export default router;
